// utils/opentelemetry.js
import { registerInstrumentations } from '@opentelemetry/instrumentation'
import { XMLHttpRequestInstrumentation } from '@opentelemetry/instrumentation-xml-http-request'
import {
  BatchSpanProcessor,
  WebTracerProvider
} from '@opentelemetry/sdk-trace-web'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'
import { Resource } from '@opentelemetry/resources'

// Registering instrumentations
registerInstrumentations({
  instrumentations: [
    // new DocumentLoadInstrumentation(),
    // new UserInteractionInstrumentation(),
    new XMLHttpRequestInstrumentation({
      applyCustomAttributesOnSpan: (span, xhr) => {
        span.setAttribute('custom', 'hello')
      },
      ignoreUrls: [/\/lastDay/] // 配置不需要跟踪的请求
    })
  ]
})

const collectorOptions = {
  url: '/api/v1/traces', // url is optional and can be omitted - default is http://localhost:4318/v1/traces
  headers: {}, // an optional object containing custom headers to be sent with each request
  concurrencyLimit: 10 // an optional limit on pending requests
}

const serviceName = 'epayment-front-sit' // 应用名称根据实际应用变更

const resource = new Resource({ 'service.name': serviceName })
const provider = new WebTracerProvider({ resource })
const exporter = new OTLPTraceExporter(collectorOptions)
provider.addSpanProcessor(
  new BatchSpanProcessor(exporter, {
    // The maximum queue size. After the size is reached spans are dropped.
    maxQueueSize: 100,
    // The maximum batch size of every export. It must be smaller or equal to maxQueueSize.
    maxExportBatchSize: 10,
    // The interval between two consecutive exports
    scheduledDelayMillis: 500,
    // How long the export can run before it is cancelled
    exportTimeoutMillis: 30000
  })
)

provider.register()
